/*
 * 登录首页
 */
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_styled_toast/flutter_styled_toast.dart';
import 'package:flutter_svg/svg.dart';
import 'package:flutter_auth/constants.dart';
import 'package:animated_text_kit/animated_text_kit.dart';
import 'package:flutter_auth/common/util.dart';
import 'package:loading_indicator/loading_indicator.dart';
import 'package:flutter_auth/common/service.dart';
import '../../constant/globals.dart' as globals;

class LoginWidget extends StatefulWidget {
  @override
  _LoginPageState createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginWidget> {
  // 焦点
  FocusNode _focusNodeUserName = new FocusNode();
  FocusNode _focusNodePassWord = new FocusNode();
  // 用户名输入框控制器，此控制器可以监听用户名输入框操作
  TextEditingController _userNameController = new TextEditingController();
  final _formKey = GlobalKey<FormState>();
  var _password = ''; //用户名
  var _username = ''; //密码
  var _isShowPwd = false; //是否显示密码
  var _isShowClear = false; //是否显示输入框尾部的清除按钮
  @override
  void initState() {
    //设置焦点监听
    _focusNodeUserName.addListener(_focusNodeListener);
    _focusNodePassWord.addListener(_focusNodeListener);
    //监听用户名框的输入改变
    _userNameController.addListener(() {
      // 监听文本框输入变化，当有内容的时候，显示尾部清除按钮，否则不显示
      if (_userNameController.text.length > 0) {
        _isShowClear = true;
      } else {
        _isShowClear = false;
      }
      setState(() {});
    });
    super.initState();
  }

  @override
  void dispose() {
    // TODO: implement dispose
    // 移除焦点监听
    _focusNodeUserName.removeListener(_focusNodeListener);
    _focusNodePassWord.removeListener(_focusNodeListener);
    _userNameController.dispose();
    super.dispose();
  }

  // 监听焦点
  Future _focusNodeListener() async {
    if (_focusNodeUserName.hasFocus) {
      // 取消密码框的焦点状态
      _focusNodePassWord.unfocus();
    }
    if (_focusNodePassWord.hasFocus) {
      // 取消用户名框焦点状态
      _focusNodeUserName.unfocus();
    }
  }

  // 验证用户名
  String validateUserName(value) {
    // 正则匹配手机号
    RegExp exp = RegExp(
        r'^((13[0-9])|(14[0-9])|(15[0-9])|(16[0-9])|(17[0-9])|(18[0-9])|(19[0-9]))\d{8}$');
    if (value.isEmpty) {
      return '用户名不能为空!';
    } else if (!exp.hasMatch(value)) {
      return '请输入正确手机号';
    }
    return null;
  }

  // 验证密码
  String validatePassWord(value) {
    if (value.isEmpty) {
      return '密码不能为空';
    } else if (value.trim().length < 6) {
      return '密码长度不正确';
    }
    return null;
  }

  Widget build(BuildContext context) {
    ScreenUtil.instance = ScreenUtil(width: 750, height: 1334)..init(context);
    // 输入文本框区域
    Widget inputTextArea = new Container(
      margin: EdgeInsets.only(left: 20, right: 20),
      decoration: new BoxDecoration(
          borderRadius: BorderRadius.all(Radius.circular(8)),
          color: Colors.white),
      child: new Form(
        key: _formKey,
        child: new Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            new TextFormField(
              controller: _userNameController,
              focusNode: _focusNodeUserName,
              //设置键盘类型
              keyboardType: TextInputType.number,
              decoration: InputDecoration(
                labelText: "用户名",
                hintText: "请输入手机号",
                prefixIcon: Icon(Icons.person),
                //尾部添加清除按钮
                suffixIcon: (_isShowClear)
                    ? IconButton(
                        icon: Icon(Icons.clear),
                        onPressed: () {
                          // 清空输入框内容
                          _userNameController.clear();
                        },
                      )
                    : null,
              ),
              //验证用户名
              validator: validateUserName,
              onChanged: (String value) {
                setState(() {
                  _username = value;
                });
              },
            ),
            new TextFormField(
              focusNode: _focusNodePassWord,
              decoration: InputDecoration(
                labelText: "密码",
                hintText: "请输入密码",
                prefixIcon: Icon(Icons.lock),
                // 是否显示密码
                suffixIcon: IconButton(
                  icon: Icon(
                      (_isShowPwd) ? Icons.visibility : Icons.visibility_off),
                  // 点击改变显示或隐藏密码
                  onPressed: () {
                    setState(() {
                      _isShowPwd = !_isShowPwd;
                    });
                  },
                ),
              ),
              obscureText: !_isShowPwd,
              //密码验证
              validator: validatePassWord,
              onChanged: (String value) {
                setState(() {
                  _password = value;
                });
              },
            )
          ],
        ),
      ),
    );
    return Scaffold(
      backgroundColor: Colors.white,
      // 外层添加一个手势，用于点击空白部分，回收键盘
      body: new GestureDetector(
        onTap: () {
          _focusNodePassWord.unfocus();
          _focusNodeUserName.unfocus();
        },
        child: new ListView(
          children: [
            new SizedBox(
              height: ScreenUtil().setHeight(80),
            ),
            LogoImageArea(),
            new SizedBox(
              height: ScreenUtil().setHeight(70),
            ),
            inputTextArea,
            new SizedBox(
              height: ScreenUtil().setHeight(80),
            ),
            LoginButtonArea(
              focusNodeUserName: _focusNodeUserName,
              focusNodePassWord: _focusNodePassWord,
              formKey: _formKey,
              username: _username,
              password: _password,
            ),
            // loginButtonArea, // 登录按钮
            new SizedBox(
              height: ScreenUtil().setHeight(60),
            ),
          ],
        ),
      ),
    );
  }
}

/*
 * 登录页面的log图标
 */
class LogoImageArea extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    Size size = MediaQuery.of(context).size;
    // logo 图片区域
    return new Container(
      alignment: Alignment.topCenter,
      // 设置图片为圆形
      child: Container(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            SizedBox(
              width: 250.0,
              child: ColorizeAnimatedTextKit(
                  text: [
                    "日志系统",
                    "记得填写哦",
                    "天天开心",
                  ],
                  textStyle: TextStyle(
                      fontSize: 20.0,
                      fontFamily: "Horizon",
                      fontWeight: FontWeight.w700),
                  colors: [
                    Colors.purple,
                    Colors.blue,
                    Colors.yellow,
                    Colors.red,
                  ],
                  textAlign: TextAlign.center,
                  alignment:
                      AlignmentDirectional.topStart // or Alignment.topLeft
                  ),
            ),
            SizedBox(height: size.height * 0.03),
            SvgPicture.asset(
              "assets/icons/login.svg",
              height: size.height * 0.35,
            )
          ],
        ),
      ),
    );
  }
}

/*
 * 登录按钮widget
 */
class LoginButtonArea extends StatefulWidget {
  FocusNode focusNodeUserName;
  FocusNode focusNodePassWord;
  final formKey;
  var password;
  var username;
  LoginButtonArea({
    Key key,
    this.focusNodeUserName,
    this.formKey,
    this.focusNodePassWord,
    this.username,
    this.password,
  }) : super(key: key);
  _LoginButtonAreaState createState() {
    return _LoginButtonAreaState();
  }
}

class _LoginButtonAreaState extends State<LoginButtonArea> {
  bool loading = false;
  @override
  Widget build(BuildContext context) {
    return new Container(
      margin: EdgeInsets.only(left: 20, right: 20),
      height: 45.0,
      child: new RaisedButton(
        color: kPrimaryColor,
        child: loginDesc(),
        // 设置按钮圆角
        shape:
            RoundedRectangleBorder(borderRadius: BorderRadius.circular(10.0)),
        onPressed: () {
          //点击登录按钮，解除焦点，回收键盘
          widget.focusNodePassWord.unfocus();
          widget.focusNodeUserName.unfocus();
          if (widget.formKey.currentState.validate()) {
            setState(() {
              loading = true;
            });
            //todo 登录操作
            sysLog(widget.username, widget.password, context); // 日志登录
          }
        },
      ),
    );
  }

  /*
   * 登录描述 
   */
  Widget loginDesc() {
    if (loading) {
      return Container(
        alignment: Alignment.center,
        padding: EdgeInsets.all(4.0),
        child: LoadingIndicator(
          indicatorType: Indicator.ballClipRotateMultiple,
          color: kPrimaryLightColor,
        ),
      );
    } else {
      return Text(
        "登录",
        style: TextStyle(color: Colors.white),
      );
    }
  }

  /*
   * 日志登录 
   */
  void sysLog(username, password, context) async {
    try {
      password = Util.base64Encode(password);
      final jsonResponse =
          await userLogin({"phoneNum": username, "password": password})
              .then((result) {
        return result;
      }); // 用户登录服务
      if (jsonResponse['state']) {
        resetHttpHeader(); // 重置请求头
        globals.userInfo = jsonResponse;
        globals.header['token'] = jsonResponse['data']['token'];
        globals.header['Cookie'] =
            '${jsonResponse['data']['baseCookieKey']}=${jsonResponse['data']['token']}';
        globals.header['userId'] = jsonResponse['data']['id'];
        var name = Uri.encodeComponent(jsonResponse['data']['name']);
        globals.header['userName'] = name;
        setState(() {
          loading = false;
        });
        Navigator.pushReplacementNamed(context, "/indexWidget");
      } else {
        showToast(
          jsonResponse['msg'],
          context: context,
          animation: StyledToastAnimation.slideFromBottom,
          reverseAnimation: StyledToastAnimation.slideToBottom,
          startOffset: Offset(0.0, 3.0),
          reverseEndOffset: Offset(0.0, 3.0),
          position: StyledToastPosition.bottom,
          duration: Duration(seconds: 4),
          animDuration: Duration(seconds: 1),
          curve: Curves.elasticOut,
          reverseCurve: Curves.fastOutSlowIn,
        );
        setState(() {
          loading = false;
        });
      }
    } catch (e) {
      print(e);
    }
  }
}
